<template>
  <div class="container">
    <el-row type="flex" justify="center">
      <el-col :span="20">
        <el-row class="video-box">
          <div class="title">
            <h2>{{ lesson.title }}</h2>
            <div>
              课程评分
              <el-rate
                v-model="lesson.score"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
              >
              </el-rate>
            </div>
          </div>
          <el-card :body-style="{ padding: '0px' }">
            <video
              id="myVideo"
              class="video-js vjs-big-play-centered"
              controls
              preload="auto"
              :poster="lesson.coverUrl"
            >
              <source type="video/mp4" :src="this.src" />
            </video>
            <el-row class="bottom" type="flex" justify="space-between">
              <el-col :span="4">
                <el-row type="flex" justify="start">
                  <span>课程评价：</span>
                  <el-rate
                    :disabled="rateDisable"
                    @change="rateChange"
                    v-model="value2"
                  >
                  </el-rate>
                </el-row>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <el-col :span="4">
                    <!-- <el-link>收藏</el-link> -->
                  </el-col>
                  <el-col :span="2">
                    <el-divider direction="vertical"></el-divider>
                  </el-col>
                  <el-col :span="8"> 主讲教师： </el-col>
                  <el-col :span="10">
                    <el-link>{{ lesson.teacher.realName }}</el-link>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-card>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="14">
            <el-divider content-position="left"> 课程简介 </el-divider>
            <el-row class="desc">
              {{ lesson.content }}
            </el-row>
          </el-col>
          <el-col :span="10">
            <el-card
              :body-style="{ padding: '0px' }"
              class="period"
              header="课时"
              shadow="never"
            >
              <el-row
                v-for="(item, index) in lesson.lessonPeriodPOS"
                :key="item.id"
                @click.native="switchLessonPeriod(index)"
                class="item"
              >
                <el-col :span="3">
                  <span style="font-size: 12px"> {{ item.duration }} </span>
                </el-col>
                <!-- <el-col :span="3"> 第 {{ item }} 课时</el-col> -->
                <el-col :span="21">
                  <span>p{{ index + 1 }}&ensp;</span>
                  <span>{{ item.title }}</span>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getById, list, update, add } from "@/api/common";
import { timeMeter } from "@/utils/time";

export default {
  data() {
    return {
      lesson: {
        id: "",
        subjectId: "",
        title: "",
        content: "",
        coverUrl: "",
        score: "",
        teacher: {
          realName: "",
        },
        lessonPeriodPOS: [
          {
            id: "",
            duration: "",
            title: "",
            url: "",
          },
        ],
      },
      value2: undefined,

      src: "//vjs.zencdn.net/v/oceans.mp4",

      myPlayer: undefined,

      rateDisable: false,

      tmp: {
        score: undefined,
        scorePeople: undefined,
      },

      watchingPeriodId: undefined,

      watchingStartTime: undefined,

      pauseTime: undefined,

      duration: undefined,
    };
  },
  created() {
    this.initVideo();

    const lesson = this.$store.getters["lesson/currentLesson"];

    this.tmp.score = lesson.score;
    this.tmp.scorePeople = lesson.scorePeople;

    this.lesson.coverUrl = lesson.coverUrl;
    this.lesson.content = lesson.content;
    this.lesson.title = lesson.title;
    this.lesson.score = (lesson.score / lesson.scorePeople).toFixed(2);
    this.lesson.id = lesson.id;
    this.lesson.subjectId = lesson.subjectId;

    const id = lesson.teacherId;
    getById("user", { id }).then((res) => {
      this.lesson.teacher.realName = res.realName;
    });

    const lessonId = lesson.id;
    list("courseLessonPeriod", { lessonId }).then((res) => {
      const tmp = [];
      res.forEach((element) => {
        element.duration = timeMeter(element.duration);
        tmp.push(element);
      });
      this.lesson.lessonPeriodPOS = tmp;

      this.switchVideo(tmp[0].url, tmp[0].id);
    });
  },
  methods: {
    initVideo() {
      this.$nextTick(() => {
        let myPlayer = this.$video(document.getElementById("myVideo"), {
          //确定播放器是否具有用户可以与之交互的控件。没有控件，启动视频播放的唯一方法是使用autoplay属性或通过Player API。
          controls: true,
          //自动播放属性,muted:静音播放
          autoplay: false,
          //建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
          preload: "auto",
          //设置视频播放器的显示宽度（以像素为单位）
          width: "1600",
          //设置视频播放器的显示高度（以像素为单位）
          height: "700",
          controlBar: {
            playToggle: true,
          },

          // sources: [
          //   {
          //     src: this.src,
          //   },
          // ],
        });
        this.myPlayer = myPlayer;

        myPlayer.on("play", () => {
          const studentId = this.$store.getters["user/id"];
          const lessonId = this.lesson.id;
          add("recordStudentLesson", { studentId, lessonId });
          this.watchingStartTime = new Date();
        });

        myPlayer.on("ended", () => {
          this.duration += Math.round((this.pauseTime - this.watchingStartTime) / 1000);
        });

        myPlayer.on("pause", () => {
          this.pauseTime = new Date();
          this.duration += Math.round((new Date() - this.watchingStartTime) / 1000);
        })
      });
    },

    switchVideo(url, id, seekTime = 0, qualityNname) {
      let $video = document.getElementById(`myVideo_html5_api`);
      // 设置视频的src
      $video.setAttribute("src", url);

      this.watchingPeriodId = id;

      this.myPlayer.load();
    },

    switchLessonPeriod(index) {
      this.switchVideo(
        this.lesson.lessonPeriodPOS[index].url,
        this.lesson.lessonPeriodPOS[index].id
      );
    },

    rateChange(rate) {
      let score = this.tmp.score;
      let scorePeople = this.tmp.scorePeople;

      score += rate;
      scorePeople += 1;
      const id = this.lesson.id
      update("courseLesson", { id, score, scorePeople }).then(() => {
        this.rateDisable = true;

        getById("courseLesson", { id } ).then(res => {
          
        })
      });
    },

    record() {
      const progress = this.myPlayer.currentTime();
      const duration = this.duration;
      const lessonId = this.lesson.id;
      const sutdentId = this.$store.getters["user/id"];
      const lessonPeriodId = this.watchingPeriodId;
      const subjectId = this.lesson.subjectId;

      add('recordStudentLearn', {
        progress,
        duration,
        lessonId,
        sutdentId,
        lessonPeriodId,
        subjectId
      });
    },
  },

  beforeDestroy() {
    this.record();
  }
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 90vh;

  padding-bottom: 2rem;

  .el-divider__text {
    background-color: #edf3ff;
  }
}

.video-box {
  margin-top: 2rem;

  .title {
    display: flex;
    margin: 0.5rem;
    justify-content: space-between;
  }

  .bottom {
    padding: 0.8rem;
  }
}

.desc {
  p {
    text-indent: 50px;
    text-align: justify;
    letter-spacing: 1px;
    word-wrap: break-word;
  }
}

.period {
  margin-top: 1rem;

  .item {
    padding: 0.5rem 1rem 0.5rem 1rem;
    text-align: start;

    &:hover {
      background: #66b1ff;
      color: #fff;
    }
  }
}
</style>